/**
 * This file is Copyright © 2008 Software Craftsmen Limited. All Rights Reserved.
 */
package com.softwarecraftsmen.orogeny.execution;

import com.softwarecraftsmen.orogeny.BuildScript;
import com.softwarecraftsmen.orogeny.UpperCaseEnvironmentVariableOnWindows;
import static com.softwarecraftsmen.orogeny.operatingSystems.OperatingSystemFamily.currentOperatingSystemFamily;
import org.jetbrains.annotations.NotNull;

import static java.util.Collections.emptySet;
import java.util.LinkedHashSet;
import static java.util.Locale.UK;
import java.util.Set;

public class UpperCaseEnvironmentVariableOnWindowsProcessor
{
	private final Set<String> environmentVariablesToTransform;

	public UpperCaseEnvironmentVariableOnWindowsProcessor(final @NotNull Class<? extends BuildScript> buildScript)
	{
		environmentVariablesToTransform = environmentVariablesToTransform(buildScript);
	}

	@NotNull
	public String transformEnvironmentVariableName(final @NotNull String environmentVariableName)
	{
		final String asUpperCaseForm = toUpperCase(environmentVariableName);
		if(environmentVariablesToTransform.contains(asUpperCaseForm))
		{
			return asUpperCaseForm;
		}
		return environmentVariableName;
	}

	@NotNull
	private static Set<String> environmentVariablesToTransform(final Class<? extends BuildScript> buildScript)
	{
		if (currentOperatingSystemFamily().isNotWindowsCompatible())
		{
			return emptySet();
		}
		final UpperCaseEnvironmentVariableOnWindows upperCaseEnvironmentVariableOnWindowsProcessor = buildScript.getAnnotation(UpperCaseEnvironmentVariableOnWindows.class);

		if (upperCaseEnvironmentVariableOnWindowsProcessor == null)
		{
			return emptySet();
		}

		return new LinkedHashSet<String>()
		{{
			for (String environmentVariableName : upperCaseEnvironmentVariableOnWindowsProcessor.value())
			{
				add(toUpperCase(environmentVariableName));
			}
		}};
	}

	private static String toUpperCase(final String environmentVariableName) {return environmentVariableName.toUpperCase(UK);}
}
